//全局变量---------------------------------------------------------------
var globalList = new LinkedList(); 	//所有牌
var historyList= new LinkedList(); 	//备份所有牌，用于撤消
var cancelList = new LinkedList();		//撤消链表
var hintList   = new LinkedList();		//提示列表

var showList   = new ListArray(10);	//10列牌	
var sendList   = new ListArray(6); 	//6组发牌

var moveList;

var gameStart = 0;

var hGap = 18;		//牌列横向间距
var vGap = 7;		//背面牌纵向间距
var vGapf = 28;

var pokerw = 71;
var pokerh = 96;

var showHTML = new Array(10);	//10列牌html代码
var sendHTML = "";
var successHTML = "";			//成功后牌列html代码

var mode=1;			//1.初级    2.中级    3.高级
var sound=0;		//声音

var emptyNum;		//空列的个数
var si;			//要发的牌组，6组，0-5

var score;		//分数
var opn;		//操作数
var succNum;	//收起列数

var list;
var coverDiv;
 

var ua = navigator.userAgent.toLowerCase();
var ISIE=ua.match(/msie ([\d.]+)/);
var ISFF=ua.match(/firefox\/([\d.]+)/);
var ISGG=ua.match(/chrome\/([\d.]+)/);
var ISOP=ua.match(/opera.([\d.]+)/);
var ISSF=ua.match(/version\/([\d.]+).*safari/);

if(ISIE) document.execCommand("BackgroundImageCache",false,true);

var playerHTMLIE;
var playerHTMLFF;
//牌类-----------------------------------------------------------------
function poker(value, type, isfront, visible)
{
	var numargs = arguments.length;
	this.value = value;
	this.type = type; 		//1.黑桃	2.红桃	3.梅花	4.方块
	
	//默认isfront=0,visible=1
	if(numargs < 3)
	{
       this.isfront = 0;
       this.visible = 1;
    }
    else if(numargs < 4)
    {
		this.visible = 1;
	}
	else
	{
       this.isfront = isfront;
       this.visible = visible;	
    }
    
    this.idx = 0;		//在第几列牌，0开始
    this.idy = 0;		//在牌列中的位置，0开始
    this.moveable = 0;	//是否能移动
    this.top = 0;		//坐标top
    this.left = 0;		//坐标left
    this.width = pokerw;	//牌宽
    this.height = pokerh;	//牌高
    this.zindex = 1;	//z向
    this.id = 1;		//所有牌的唯一编号
    this.list = "show";	//
    
    this.html = "";		//牌的html代码

	this.build  = function()	//编译html
	{	

			
			var backpoker=
				 "id=\"poker-"+this.id+"\" "
				+"style=\"width:"+(this.width)+"px;"
				+"height:"+(this.height)+"px;"
				+"position:absolute;cursor:default;"
				+"left:"+this.left+"px;"
				+"top:"+this.top+"px;"
				+"z-index:" + this.zindex +";\" class=\"backPoker\""; 
				
			var frontpoker=
				  "id=\"poker-"+this.id+"\" "
				 +"style=\"width:"+(this.width)+"px;"
				 +"height:"+(this.height)+"px;"
				 +"position:absolute;background:url('http://jsspider.googlecode.com/svn/trunk/ig/images/normal/t"+this.type+"v"+this.value+".gif') no-repeat;"
				 +"cursor:default;"
				 +"left:"+this.left+"px;"
				 +"top:"+this.top+"px;"
				 +"z-index:" + this.zindex +";\" "; 
			
			this.html="<div ";
			if(this.isfront) 	this.html += frontpoker;
			else				this.html += backpoker;
			
			if(this.moveable)
			{
				this.html +=
					 "onmousedown='startDrag(this,"+this.idx+","+this.idy+","+this.moveable+",event)' "
					/*+"onmouseup='stopDrag(this,"+this.idx+","+this.idy+",event)' "
					+"onmousemove='drag(this,"+this.moveable+")' "*/
					+"onlosecapture='loseCapture(this,"+this.idx+","+this.idy+")' ";
			}
			this.html += ">";
			
			this.html += "</div>\n";	
	};
	
	//牌层对象--------------------
	this.obj = function()
	{
		return document.getElementById("poker-"+this.id);
	};
	//复制牌节点------------------
	this.copyto = function(target)
	{
		target.value	=this.value;
		target.type 	=this.type;
		target.isfront	=this.isfront;
		target.visible	=this.visible;
		target.idx		=this.idx;
		target.idy		=this.idy;
		target.moveable	=this.moveable;
		target.top		=this.top;
		target.left		=this.left;
		target.width	=this.width;
		target.height	=this.height;
		target.zindex	=this.zindex;
		target.id		=this.id;
		target.list		=this.list;
		target.html		=this.html;
		target.build	=this.build;
		target.obj		=this.obj;
		target.copyto	=this.copyto; 
		target.pokertype=this.pokertype;
		target.pokervalue=this.pokervalue;
	};
}

//撤消节点---------------------------------------------
function CancelNode(fid,tid,fl,tl)
{
	this.from = fid;
	this.to = tid; 
	
	this.flist = new LinkedList();
	this.tlist = new LinkedList(); 
	 
	for(i=0;i<fl.size();i++)
	{
		var fpoker = new poker;
		fl.get(i).copyto(fpoker);
		this.flist.add(fpoker); 
	} 
	for(i=0;i<tl.size();i++)
	{
		var tpoker = new poker;
		tl.get(i).copyto(tpoker);
		this.tlist.add(tpoker);
	}  
	 
	this.flist.frontStart=fl.frontStart;
	this.flist.activeStart=fl.activeStart;
	this.flist.lx=fl.lx;
	this.flist.ly=fl.ly;
	this.flist.frontnum=fl.frontnum;
	this.flist.vGap=fl.vGap;			
		
	this.tlist.frontStart=tl.frontStart;
	this.tlist.activeStart=tl.activeStart;
	this.tlist.lx=tl.lx;
	this.tlist.ly=tl.ly;
	this.tlist.frontnum=tl.frontnum;
	this.tlist.vGap=tl.vGap;	
		
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function init()
{
	//两副牌初始化-------------------
	var pokerValue,pokerType;
	var playPoker;
	var cancelPoker;
	var tmode;
	if(mode==1) tmode=1;
	if(mode==2) tmode=2;
	if(mode==3) tmode=4;
	pokerValue= 1;
	pokerType = 1;
	var k=1;
	for(i=1;i<=104;i++)
	{
		playPoker   = new poker(pokerValue,pokerType);
		cancelPoker = new poker(pokerValue,pokerType);
		if(pokerType<tmode)pokerType++; 
		else pokerType=1;
		k++;	
		if(k > 4)	
		{
			pokerValue++;
			k=1;
		}
		if(pokerValue > 13 )
			pokerValue = 1;
		globalList.add(playPoker);
		historyList.add(cancelPoker);
	}
	
	//创建movelist
	moveList=document.createElement("div");
	moveList.style.cssText="width:71;height:96px;position:absolute;top:0px;left:0px;padding:1px;z-index:-1;";


	
}

function gameinit()
{	
	//初始化值
	emptyNum=0;		//空列的个数
	si=0;			//要发的牌组，6组，0-5

	score =500;		//分数
	opn  = 0;		//操作数
	succNum = 0;	//收起列数	
	
	var i,j,k=0;
	//打乱排序 
	for(i=0;i<104;i++)
	{
		var t;
		t = Math.floor(Math.random()*(104-1)+1); 
		globalList.swap(i,t); 
		historyList.swap(i,t);
	}
	//布置位置
	for(i=0;i<10;i++)
	{
		for(j=0;j<=(i<4?4:3);j++)
		{  
			showList[i].add(globalList.get(k));
			showList[i].get(j).idx = i;
			showList[i].get(j).idy = j;
			showList[i].get(j).id = k;  
			showList[i].get(j).top = parseInt((j)*vGap);
			showList[i].get(j).zindex = parseInt(j+1); 
			k++;  
			showList[i].get(j).build();
		}
	}
	for(i=0;i<=5;i++)
	{
		for(j=0;j<10;j++)
		{  
			sendList[i].add(globalList.get(k));
			sendList[i].get(j).id = k; 
			sendList[i].get(j).zindex = 1; 
			sendList[i].get(j).build();
			k++; 			
		}
	}
	//显示 
	var sendListStyle="width:71px;height:96px;position:absolute;"; 

	for(i=0;i<10;i++)
	{
		showHTML[i]="";
		for(j=0;j<showList[i].size();j++)
			showHTML[i]+=showList[i].get(j).html; 
	}    
	
	sendHTML="";
	for(i=0;i<6;i++)
	{
		sendHTML += "<div id=\"sendlist"+(i+1)
				 +"\" style=\""+sendListStyle
				 +"left:"+parseInt(i*12)
				 +"px; z-index:"+parseInt(6-i)+"\""
				 //+" onmousedown='preSend("+i+")'"
				 +" onclick='aniSend("+i+",0)'  class=\"backPoker\""
		+">\n</div>";   
	}    
}
function onOffSend(open,sid)
{	 
	document.onkeydown=function (ev)
	{	
		if(!ev) ev=window.event;
		if(open)
		{

			if(ev.keyCode == 90) cancel();			//z
			if(ev.keyCode == 83) onSound();			//r
			if(ev.keyCode == 82) onStart(1);		//r
			if(ev.keyCode == 76) onLevel(1);		//l
			if(ev.keyCode == 72) onHint();			//h				 	 
			if(ev.keyCode == 68 && si<6) onSend();	//d
			if(ev.keyCode == 65) showAbout();		//a
		}
		else
		{
			if(ev.keyCode == 90) return;
			if(ev.keyCode == 83) return;
			if(ev.keyCode == 82) return; 
			if(ev.keyCode == 76) return;
			if(ev.keyCode == 72) return;
			if(ev.keyCode == 68 && si<6) return;
			if(ev.keyCode == 65) return;	 
		}
	};
	document.getElementById("sendlist"+(sid+1)).onclick = function()
	{		
		if(open)	aniSend(sid,0); 
		else		return;
	};

}

function update()
{
	for(i=0;i<10;i++)
	{
		list=document.getElementById("list"+(i+1));	 
		list.innerHTML=showHTML[i];
	} 
	oSendField.innerHTML=sendHTML;
	aniSend(0,1); 
	oGameField.appendChild(moveList);
}
	
var oGameField;
var oSendField;
var oPanel;	 
var oSound;
var oYouWin;
var oLevel;
var oCancel;
window.onload=function restart() { 
	oGameField=document.getElementById("gamefield");
	oSendField=document.getElementById("sendfield");  
	oPanel=document.getElementById("panel"); 
	oSound=document.getElementById("sound"); 
	oYouWin=document.getElementById("youWin");
	oCancel=document.getElementById("cancel");
	oLevel=document.getElementById("level");
	
	onSound();  //声音 
	
	
	oGameField.style.left = hGap +"px";
	for(var i=0;i<10;i++)	
	{
		list=document.getElementById("list"+(i+1));	
		list.style.left=i*(hGap+pokerw)+"px";
	}
	document.getElementById("levelWin").style.display="block";
	oLevel.removeChild(oCancel);
	coverDiv = document.getElementById("cover");
	coverDiv.style.display="block";
	document.getElementsByName("cancel").disabled = true;
	
	
	if(ISSF) document.body.style.KhtmlUserSelect="none";
	if(ISFF) document.documentElement.style.MozUserSelect="none";
	if(ISIE||ISGG) document.onselectstart=function(){return false;};
 
}; 
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
var levelInit = 0; 
var isConfirm = 0; 
var restartAlert = 0;
function onStart(r)
{  
	if(lang == "cn")
	{
		if(restartAlert && r==1)	isConfirm = confirm('是否开始新游戏?'); 
		if(restartAlert && r==2)	isConfirm = confirm('恭喜恭喜，你赢了\n是否开始新一轮游戏?'); 
	}
	if(lang == "en")
	{
		if(restartAlert && r==1)	isConfirm = confirm('Are you sure you want to start a new game?');  
		if(restartAlert && r==2)	isConfirm = confirm('Congragulations，you won\nDo you want to start another game?'); 
	}
	if(isConfirm || !restartAlert)
	{ 	 
		var osucc = document.getElementById("successfield");
		osucc.innerHTML="";
		successHTML="";
		oYouWin.style.display = "none";
		for(var i=0;i<104;i++)
		{
			globalList.get(i).isfront = 0;
			globalList.get(i).moveable = 0;  
			historyList.get(i).isfront = 0;
			historyList.get(i).moveable = 0;  
		}
		
		for(i=0;i<10;i++) 
		{
			showList[i].clear();
			showList[i].frontStart=0;
			showList[i].activeStart=0;
			showList[i].lx=0;
			showList[i].ly=0;
			showList[i].frontnum=0;	  
			showList[i].vGap=28;	
		}	
		for(i=0;i<=5;i++)  
			sendList[i].clear();
		gameStart = 0;
		
		
		gameinit();  	
		flushScore();
		update();	
		restartAlert = 0;
	} 
}
function onSound()
{
//声音
	if(!sound)
	{
		playerHTMLIE="<object id=\"WMP\" width=\"0px\" height=\"0px\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112\" align=\"baseline\" border=\"0\" standby=\"Loading Microsoft Windows Media Player components...\" type=\"application/x-oleobject\"><param name=\"URL\" value=\"\"><param name=\"autoStart\" value=\"true\"><param name=\"invokeURLs\" value=\"false\"><param name=\"playCount\" value=\"1\"></object>";

		playerHTMLFF="<embed id=\"WMP\"  mastersound align=\"baseline\" border=\"0\" width=\"0px\" height=\"0px\" type=\"application/x-mplayer2\" pluginspage=\"\" name=\"abcplayer\" autostart=\"1\" src=\"\"></embed>";
		if(ISIE) oSound.innerHTML = playerHTMLIE;
		if(lang=="cn")
			document.getElementById("soundBn").innerHTML = "关闭声音(for IE)　(<u>S</u>)";
		if(lang=="en")
			document.getElementById("soundBn").innerHTML = "Sound Off(for IE)　(<u>S</u>)";
		sound = 1;
	}
	else
	{
		playerHTMLIE="";
		playerHTMLFF="";
		if(ISIE) oSound.innerHTML = playerHTMLIE;
		if(lang=="cn")
			document.getElementById("soundBn").innerHTML = "打开声音(for IE)　(<u>S</u>)";
		if(lang=="en")
			document.getElementById("soundBn").innerHTML = "Sound On(for IE)　(<u>S</u>)";
		sound = 0;
	}

}
function onSend()
{
	if(si<6)
	{
		aniSend(si,0);	
	}
}
function onCancel()
{
	cancel();
}
function onLevelSubmit()
{
	var level= document.getElementsByName("level"); 
	for(var i=0;i<level.length;i++)
	{
		if(level[i].checked)			
		mode = parseInt(level[i].value);
	}  
	if(levelInit )
	{
		if(restartAlert)	
		{
			if(lang == "cn") isConfirm = confirm('是否开始新游戏?');
			if(lang == "en") isConfirm = confirm('Are you sure you want to start a new game?'); 
		}
		if(isConfirm || !restartAlert)
		{
			globalList.clear();
			historyList.clear();
			init();  
			onStart(); 
		}
	}
	else
	{ 
		init();	
		gameinit();
		update();
		oLevel.appendChild(oCancel);
	} 
	document.getElementById("levelWin").style.display="none";
	onOffSend(1,si);
	
} 
function onLevelCancel()
{
	document.getElementById("levelWin").style.display="none";
	onOffSend(1,si);
}
function onLevel()
{
	levelInit = 1;
	document.getElementById("levelWin").style.display="block";
	coverDiv.style.display="none";
	
	onOffSend(0,si);
	
	document.getElementsByName("cancel").disabled = true;
}
function onHint()
{
	hint();
}

///////////////////////////////////////////////////////////
/*---------------------拖动---------------------*/
var x0=0,y0=0,x1=0,y1=0;
var clickflag=false;
var tzindex; 
var ev; 
//开始拖动;
function startDrag(obj,idx,idy,mable,ev)
{  
 
	if(mable)
	{ 		   
		if(!ev) ev=window.event;  
		
		//记录鼠标和层位置;
		x0 = ev.clientX;
		y0 = ev.clientY;
		moveList.style.left = idx*(hGap+pokerw) +"px"; 
		moveList.style.zIndex = 100; 
		x1 = parseInt(moveList.style.left);
		y1 = parseInt(obj.style.top);
		tzindex= obj.style.zIndex;
		clickflag = true; 
				
		for(var i=idy;i<showList[idx].size();i++)
			moveList.appendChild(showList[idx].get(i).obj());
		
		if(document.addEventListener){ 
            document.addEventListener('mousemove', drag, true); 
            document.addEventListener('mouseup', stopDrag, true); 
        } else if(document.attachEvent){ 
            document.attachEvent('onmousemove', drag); 
            document.attachEvent('onmouseup', stopDrag); 
        } 
        if(ISIE) obj.setCapture();
		else window.onblur=function(){stopDrag(ev);}; 
	} 

	//拖动;
	function drag(ev)
	{  
		if(clickflag)
		{  	  
			if(!ev) ev=window.event; 
			moveList.style.left = x1 + ev.clientX - x0 +"px";
			moveList.style.top  = ev.clientY - y0 +"px"; 
		} 
	}
	//停止拖动;
	function stopDrag(ev)
	{
		if(clickflag)
		{			
			if(!ev) ev=window.event; 
			 
			if(ISIE) obj.releaseCapture();
			
			clickflag=false; 
			moveList.style.left = idx*(hGap+pokerw) +"px";
			moveList.style.top = 0 +"px";	
			moveList.style.zIndex = 0; 
			
			obj.style.left = 0 +"px";
			obj.style.zIndex=tzindex;
				
			list=document.getElementById("list"+(idx+1)); 
			
			for(var i=idy;i<showList[idx].size();i++)
				list.appendChild(showList[idx].get(i).obj()); 		
				 
			if(moveBingo(idx,idy,ev)) moveAB(idx,idy); 
			
            if(document.removeEventListener){ 
                document.removeEventListener('mousemove', drag, true); 
                document.removeEventListener('mouseup', stopDrag, true); 
            } else if(document.detachEvent){ 
                document.detachEvent('onmousemove', drag); 
                document.detachEvent('onmouseup', stopDrag); 
            } 			
		}
	}	
}
//突发情况forIE
function loseCapture(obj,idx,idy)
{
	
	if(clickflag)
	{
		if(ISIE) obj.releaseCapture();
		clickflag=false; 
		moveList.style.left = idx*(hGap+pokerw) +"px";
		moveList.style.top = 0 +"px";	
		moveList.style.zIndex = 0; 
		
		obj.style.left = 0 +"px";
		obj.style.zIndex=tzindex;
			
		list=document.getElementById("list"+(idx+1)); 
		
		for(var i=idy;i<showList[idx].size();i++)
			list.appendChild(showList[idx].get(i).obj()); 	
	}
}


/*----------------判断是否能移动----------------*/
var bingoId1,bingoId2;
var bingo1,bingo2;
function moveBingo(idx,idy,ev)
{	 
	var w=71;
	var h=96;
	var idx,idy;
	var x=10000,y=10000,xx,yy;
	var area1,area2;
	var flag=0;  
	
	//if(idx>=0)
	{
		x=showList[idx].lx + ev.clientX - x0;
		y=showList[idx].get(idy).top + ev.clientY - y0; 
	}
	
	bingoId1=-1;bingoId2=-1;
	for(i=0;i<10;i++)
	{
		if(i==idx)continue;
		xx=showList[i].lx;
		yy=showList[i].ly; 
		
		if ((x < xx) && ((xx - x) >= w)); 
		else if ((x > xx) && ((x - xx) >= w)) ;
		else if ((y < yy) && ((yy - y) >= h)) ;
		else if ((y > yy) && ((y - yy) >= h)) ;
		else 
		{
			if(!flag)	{flag=1;bingoId1=i; area1=Math.abs(xx-x)*Math.abs(yy-y);}
			else 		{		bingoId2=i;	area2=Math.abs(xx-x)*Math.abs(yy-y);} 
		}
	}   
	bingo1=0;bingo2=0;
	if(bingoId1>=0)
	{
		if(showList[bingoId1].size()==0)
		{bingo1=1;}
		else if(showList[bingoId1].last().value-showList[idx].get(idy).value==1)	
		{bingo1=1;}//alert(showList[bingoId1].last().value)
	}
	
	if(bingoId2>=0)
	{
		if(showList[bingoId2].size()==0)
		{bingo2=1;}
		else if(showList[bingoId2].last().value-showList[idx].get(idy).value==1)	
		{bingo2=1;}//alert(showList[bingoId2].last().value)
	}
	if(bingo1&&bingo2)
	{
		if(area1>=area2)	{ bingo1=1;bingo2=0;	}
		else { bingo1=0;bingo2=1;	}
	}
	//alert(bingo1)
	//alert(bingo2)
	if(bingo1||bingo2) return true; 
	
}
//刷新某列------------------------------------------
function flushlist(id)
{
	showHTML[id]="";
	for(var i=0;i<showList[id].size();i++)
	{
		showList[id].get(i).build();
		showHTML[id] += showList[id].get(i).html ;
	}	 
	return showHTML[id];
}

//移动后处理----------------------------------------
function moveAB(idx,idy)
{  
	var toi;					//目标牌列id
	if(bingo1) toi=bingoId1;
	if(bingo2) toi=bingoId2;
	if(idx>=0)
	{

		//记录返回操作 
		var cnode = new CancelNode(idx,toi,showList[idx],showList[toi]);
		cancelList.add(cnode); 
		
		restartAlert = 1;
		//移动牌列 
		var i,j;
		for(i=idy,j=0;i<showList[idx].size();i++,j++)
		{
			if(showList[toi].size()==0)		//目标牌列没有牌
			{ 
				showList[idx].get(i).top = j*showList[toi].vGap;
				showList[idx].get(i).idx = showList[toi].id;
				showList[idx].get(i).idy = j;
				showList[idx].get(i).zindex = j+1;
			}
			else							//目标牌列有牌
			{
				showList[idx].get(i).top = showList[toi].ly +showList[toi].vGap*(j+1);
				showList[idx].get(i).idx = showList[toi].last().idx;
				showList[idx].get(i).idy = showList[toi].last().idy+(j+1);
				showList[idx].get(i).zindex = showList[toi].last().idy+j+2; 
			} 
		}
		
		//目标牌列
		showList[toi].frontnum += (showList[idx].size()-idy);	
				
		var n=showList[toi].size();
		
		
			if(n==0)
			{
				showList[toi].activeStart=0;
				showList[toi].frontStart=0;				
			}
		
			else if(showList[toi].get(n-1).type != showList[idx].get(idy).type)
			{
				showList[toi].activeStart=n;
				n--; 
				while(n>=showList[toi].frontStart)
				{
					showList[toi].get(n).moveable=0; 
					n--;
				}
			}
		
		for(i=idy;i<showList[idx].size();i++)
			showList[toi].add(showList[idx].get(i));
			   
		//牌列太长，缩短
		if(showList[toi].last().top >368 && showList[toi].vGap>5) 
		{
			showList[toi].vGap = (368-showList[toi].get(showList[toi].frontStart).top)/showList[toi].frontnum;  
			if(showList[toi].vGap<14) showList[toi].vGap=14;
		
			for(i=showList[toi].frontStart+1,j=1;i<showList[toi].size();i++,j++) 
			{
				showList[toi].get(i).top = showList[toi].get(showList[toi].frontStart).top+j*showList[toi].vGap;
			}
		}
		showList[toi].ly = showList[toi].last().top;
				
							
			
				
		flushlist(toi);
		//来源牌列 
		showList[idx].frontnum -= (showList[idx].size()-idy); 
		showList[idx].remove(idy,2);		
		
		
		showHTML[idx]="";
		var k=idy-1;
		//如果全部移走，且没有背面的牌
		if(showList[idx].frontnum==0 && !idy) 
		{ 
			showList[idx].activeStart=-1; 
			showList[idx].frontStart=-1;
			showList[idx].ly = 0;
		}
		//如果全部移走，还有背面的牌
		else if(showList[idx].frontnum==0 && idy)
		{
			showList[idx].frontnum = 1; 
			showList[idx].get(k).isfront=1;
			showList[idx].get(k).moveable=1;
			showList[idx].activeStart-=1;
			showList[idx].frontStart-=1;
			showList[idx].ly = showList[idx].last().top;
		}	
		else if(idy>showList[idx].activeStart)		
		{
			showList[idx].ly = showList[idx].last().top;
		}			
		else
		{		
			showList[idx].get(k).moveable=1;	
			showList[idx].activeStart-=1;	
			
				while(k>showList[idx].frontStart && 
					   showList[idx].get(k-1).value - showList[idx].get(k).value ==1 &&
					   showList[idx].get(k-1).type==showList[idx].get(k).type)
				{
					showList[idx].activeStart-=1;
					showList[idx].get(k-1).moveable=1;	
					k--;				
				}
				
			showList[idx].ly = showList[idx].last().top;
		}

		//牌列不太长，加长
		if(showList[idx].ly < 368 && showList[idx].vGap<28) 
		{
			showList[idx].vGap = (368-showList[idx].get(showList[idx].frontStart).top)/showList[idx].frontnum;  
			if(showList[idx].vGap>28) showList[idx].vGap = 28;
			for(i=showList[idx].frontStart+1,j=1;i<showList[idx].size();i++,j++) 
			{
				showList[idx].get(i).top =  showList[idx].get(showList[idx].frontStart).top + j*showList[idx].vGap;	 
				showList[idx].ly = showList[idx].last().top;
			}
		}
					
		flushlist(idx);
		list=document.getElementById("list"+(idx+1));		
		list.innerHTML=showHTML[idx]; 
		
		list=document.getElementById("list"+(toi+1));
		list.innerHTML=showHTML[toi];
		
		
		//记分
		score--;
		opn++;
		aniSuccess(toi);
		flushScore(); 
		
	
		//初始化提示
		hNode.set(-1,-1);
	}					
}
function judgeSuccess(idx)
{		 
	var type,value;
	type = showList[idx].get(showList[idx].activeStart).type;
	value= showList[idx].get(showList[idx].activeStart).value;
	
		showList[idx].remove(showList[idx].activeStart,2);
		var k=showList[idx].activeStart-1;
		if(showList[idx].activeStart == 0)
		{
			showList[idx].activeStart=-1;
			showList[idx].frontStart=-1;
			showList[idx].frontnum=0;
			showList[idx].ly=0;
		}
		else if(showList[idx].activeStart == showList[idx].frontStart)
		{
			showList[idx].activeStart-=1;
			showList[idx].frontStart-=1;
			showList[idx].frontnum=1;
			showList[idx].ly=showList[idx].get(k).top;
			showList[idx].get(k).isfront=1;
			showList[idx].get(k).moveable=1;
		}
		else
		{
			showList[idx].frontnum-=13;
			showList[idx].get(k).moveable=1;
			showList[idx].activeStart-=1;	
			showList[idx].ly=showList[idx].get(k).top;
			
				while(k>showList[idx].frontStart && 
					  showList[idx].get(k-1).value - showList[idx].get(k).value ==1 &&
					  showList[idx].get(k-1).type==showList[idx].get(k).type)
				{
					showList[idx].activeStart-=1;
					showList[idx].get(k-1).moveable=1;	
					k--;				
				}
		}
		
		//处理牌列长度
		var i,j;
		if(showList[idx].ly < 368 && showList[idx].size()) showList[idx].vGap = (368-showList[idx].get(showList[idx].frontStart).top)/showList[idx].frontnum;  
		if(showList[idx].vGap>28 || !showList[idx].size()) showList[idx].vGap = 28;
				
		if(showList[idx].size())
			for(i=showList[idx].frontStart+1,j=1;i<showList[idx].size();i++,j++) 
			{
				showList[idx].get(i).top =  showList[idx].get(showList[idx].frontStart).top + j*showList[idx].vGap;	 
				showList[idx].ly = showList[idx].last().top;
			}	
				
		
		flushlist(idx);
		list=document.getElementById("list"+(idx+1));		
		list.innerHTML=showHTML[idx]; 		
		
		succNum++;
		successHTML+= "<div id=\"successlist"+succNum+"\" style=\"background:url('http://jsspider.googlecode.com/svn/trunk/ig/images/normal/t"+type+"v"+value+".gif') no-repeat;position:absolute;top:0px;left:"+(succNum-1)*12+"px;width:71px;height:96px;\"></div>\n";
		var osucc = document.getElementById("successfield");
		osucc.innerHTML=successHTML;
		
		score+=100;
		flushScore();
		cancelList.clear();
		
		if(succNum==8) 
		{			
			oYouWin.style.display = "block";
			if(ISIE&&sound) WMP.URL="sounds/129.wav"; 	
			restartAlert = 1;
			gameStart = 0;	
			onStart(2);
		}
		
		//初始化提示
		hNode.set(-1,-1);
}

function flushScore()
{
	var oscore = document.getElementById("sn");
	var oopn = document.getElementById("on");
	oscore.innerHTML=score;
	oopn.innerHTML=opn;
}

function check_empty()
{
	var k=0;
	for(i=0;i<10;i++)
	{
		if(showList[i].size()==0) k++;
	}
	return k;
}
 
var tempk;
function sendPokers(sid,init)
{
		tempk=1;
		sendHTML="";
		for(i=0;i<sendList[sid].size();i++)
		{ 
			var ttop;
			ttop = showList[i].last().top;
			if(init)
			{			
				showList[i].frontStart=showList[i].activeStart=(i<4?6:5)-1;
				showList[i].lx=hGap+i*(hGap+pokerw); 
				gameStart = 1;
			}
			sendList[sid].get(i).isfront = 1;
			sendList[sid].get(i).moveable = 1;
			sendList[sid].get(i).idx = i;
			sendList[sid].get(i).idy = showList[i].last().idy+1;
			sendList[sid].get(i).zindex = showList[i].last().zindex + 1;
			//sendList[sid].get(i).left = 0; 
			
			if(init)	sendList[sid].get(i).top =  ttop + vGap;
			else 	sendList[sid].get(i).top	 =  ttop + showList[i].vGap;
			sendList[sid].get(i).build();
			
			
			//------------showList----------
			var k=showList[i].size();
			if(showList[i].get(k-1).value-sendList[sid].get(i).value == 1 &&
					showList[i].get(k-1).type==sendList[sid].get(i).type);
			else
			{
				showList[i].activeStart=k;
				k--;
				while(k>=showList[i].frontStart)
				{
					showList[i].get(k).moveable=0;  
					k--;
				}
			}			 
			

			showList[i].ly = sendList[sid].get(i).top;
			
			showList[i].add(sendList[sid].get(i)); 
			showList[i].frontnum++;
			
			//处理牌列长
			var m,n;
			if(showList[i].last().top >368 && showList[i].vGap>5) 
			{
				showList[i].vGap = (368-showList[i].get(showList[i].frontStart).top)/showList[i].frontnum ;  
				if(showList[i].vGap<14) showList[i].vGap=14;
			
				for(m=showList[i].frontStart+1,n=1;m<showList[i].size();m++,n++) 
				{
					showList[i].get(m).top = showList[i].get(showList[i].frontStart).top+n*showList[i].vGap;
				}
			}			
						
			flushlist(i);	 
			
			list=document.getElementById("list"+(i+1));	
			list.innerHTML=showHTML[i];
			
			cancelList.clear();
			
		} 	
		
		var sendlist=document.getElementById("sendlist"+(sid+1));
		sendlist.style.display="none";
		for(var k=0;k<10;k++)
			aniSuccess(k);
			
		oSendField.style.zIndex = 1;
		//打开发牌响应
		onOffSend(1,sid);
		gameStart = 1;
		
		si++; 		
		  
		//初始化提示
		hNode.set(-1,-1);	 		
}


//-----------------------撤消------------------
function cancel()
{	
	if(cancelList.size()==0)	return;
	var i=cancelList.size()-1;
		
	var fid = cancelList.get(i).from;
	var tid = cancelList.get(i).to;
	
	//document.getElementById("listx").innerText=showHTML[fid]+"<br>";
	
	//清空现在的列
	showList[fid].clear();
	showList[tid].clear(); 
	  
	//从撤消列表中复制所有节点，并添加到显示列
	for(j=0;j<cancelList.get(i).flist.size();j++)
	{
		cancelList.get(i).flist.get(j).copyto(globalList.get(cancelList.get(i).flist.get(j).id));
		showList[fid].add(globalList.get(cancelList.get(i).flist.get(j).id)); 
	}		 
	
	for(j=0;j<cancelList.get(i).tlist.size();j++)
	{ 
		cancelList.get(i).tlist.get(j).copyto(globalList.get(cancelList.get(i).tlist.get(j).id));
		showList[tid].add(globalList.get(cancelList.get(i).tlist.get(j).id));
	} 
	//重设显示列属性
	showList[fid].frontStart = cancelList.get(i).flist.frontStart; 
	showList[fid].activeStart = cancelList.get(i).flist.activeStart;
	showList[fid].lx = cancelList.get(i).flist.lx;
	showList[fid].ly = cancelList.get(i).flist.ly;
	showList[fid].frontnum = cancelList.get(i).flist.frontnum;
	showList[fid].vGap = cancelList.get(i).flist.vGap;
	
	showList[tid].frontStart = cancelList.get(i).tlist.frontStart; 
	showList[tid].activeStart = cancelList.get(i).tlist.activeStart;
	showList[tid].lx = cancelList.get(i).tlist.lx;
	showList[tid].ly = cancelList.get(i).tlist.ly;
	showList[tid].frontnum = cancelList.get(i).tlist.frontnum;
	showList[tid].vGap = cancelList.get(i).tlist.vGap;


	list=document.getElementById("list"+(fid+1));		
	list.innerHTML=flushlist(fid); 
	
	list=document.getElementById("list"+(tid+1));		
	list.innerHTML=flushlist(tid); 
	 
	cancelList.remove(i,2);
	
	score--;
	opn++;
	flushScore();
}

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//动画------------------------------------------------
/*
Math.easeInOutQuad=function(t,b,c,d){
    if((t/=d/2)<1) return c/2*t*t+b;
    return -c/2*((--t)*(t-2)-1)+b;
}//二阶缓入缓出

Math.linearTween = function(t, b, c, d) { 
	return c*t/d+b; 
}//线性移动
*/
Math.easeINOutCubic = function(t, b, c, d) { 
	if ((t /= d/2)<1) { 
	return c/2*Math.pow(t, 3)+b; 
	} 
	return c/2*(Math.pow(t-2, 3)+2)+b; 
};//三阶缓入缓出
/*
Math.easeINOutQuart = function(t, b, c, d) { 
	if ((t /= d/2)<1) { 
	return c/2*Math.pow(t, 4)+b; 
	} 
	return -c/2*(Math.pow(t-2, 4)-2)+b; 
}//四阶
Math.easeINOutQuint = function(t, b, c, d) { 
	if ((t /= d/2)<1) { 
	return c/2*Math.pow(t, 5)+b; 
	} 
	return c/2*(Math.pow(t-2, 5)+2)+b; 
}//五阶
*/


var beginx; 
var beginy;
var finishx	= new Array(10);
var finishy	= new Array(10);
var changex	= new Array(10);
var changey	= new Array(10);
var duration;
var time	= new Array(10);

var isInit; 
var tsid;
function aniSend(sid,init)
{
	if(check_empty()) 
	{
		if(lang == "cn")alert("有空位时不允许发牌");
		if(lang == "en")alert("You are not allowed to deal a new row while there are any empty slots.");
		return;
	}
	else if(sid!=si) return;
	else
	{	 
		//关闭发牌响应
		onOffSend(0,sid);
		gameStart = 0;
		//蒙板
		coverDiv.style.display="block";
		
		var i,j;	
		var oSendList=document.getElementById("sendlist"+(sid+1)); 
		oSendField.style.zIndex = 2;
		beginx   = 0;
		beginy   = 0;
		duration = 30; 
		isInit   = init; 
		tsid  = sid;
			
		for(i=0;i<10;i++)
		{ 
			finishx[i] = hGap+i*(hGap+pokerw) - 759 -si*12;  
			if(init)
				finishy[i] = showList[i].last().top + vGap -495 +30;
			else
				finishy[i] = showList[i].last().top + vGapf -495 +30;
			changex[i] = finishx[i] - beginx;
			changey[i] = finishy[i] - beginy;
			time[i] = 0;
			
			sendList[sid].get(i).isfront = 1;
			sendList[sid].get(i).zindex = 10-i;
			sendList[sid].get(i).build(); 
			oSendList.innerHTML+=sendList[sid].get(i).html;
			sendList[sid].get(i).obj().style.display = "none";			
		}   
		onSendEnterFrame();
	}	
} 
function onSendEnterFrame()
{
	var i,j,k;   
	for(i=0;i<10;i++)
	{   
		if(i==0)
		{
			if(time[i]<=duration)
			{ 	 
				sendList[tsid].get(i).obj().style.display = "";
				sendList[tsid].get(i).obj().style.left = Math.easeINOutCubic(time[i]++,beginx,changex[i],duration) +"px";
				sendList[tsid].get(i).obj().style.top  = Math.easeINOutCubic(time[i]++,beginy,changey[i],duration) +"px";
			}
		}
		else if( time[i-1] > duration/3 && time[i] <= duration) 
		{  
			sendList[tsid].get(i).obj().style.display = "";
			sendList[tsid].get(i).obj().style.left = Math.easeINOutCubic(time[i]++,beginx,changex[i],duration) +"px";
			sendList[tsid].get(i).obj().style.top  = Math.easeINOutCubic(time[i]++,beginy,changey[i],duration) +"px";
			if(i==9)  
			{
				var sendlist=document.getElementById("sendlist"+(tsid+1));
				sendlist.style.background="";
			}				
        } 
	}
	
    var timer=setTimeout("onSendEnterFrame()",10); 
    
    if(parseInt(sendList[tsid].get(9).obj().style.top) == finishy[9])
    {   		
		clearTimeout(timer); 
		for(k=0;k<13;k++)	time[k]=0;
		setTimeout("sendPokers(tsid,isInit)",10); 
		coverDiv.style.display="none"; 
	}         
} 


var sbeginx; 
var sbeginy		= new Array(13);
var sfinishx;
var sfinishy;
var schangex;	
var schangey	= new Array(13); 
var stime	= new Array(13); 
var tidx;
var tz;
function aniSuccess(idx)
{	
	if(showList[idx].frontnum<13)return;
	if(showList[idx].activeStart == showList[idx].size()-13) 
	{ 
		//关闭发牌响应
		if(si<6)
		onOffSend(0,si);
		gameStart = 0;
		//蒙板
		coverDiv.style.display="block";
		
		var i,j;
		sbeginx   = 0; 	
		sbeginy	 = new Array(13);	
		
		sfinishx  = succNum*12-idx*(hGap+pokerw);
		sfinishy  = 495-30;
		
		schangex  = sfinishx-sbeginx;	 
		schangey	 = new Array(13);
		
		duration = 30; 
		stime	 = new Array(13);
		tidx     = idx;
		
		tz       = showList[idx].last().zindex;
		

		for(i=0,j=showList[idx].size()-1;i<13;i++,j--)
		{
			sbeginy[i] = showList[idx].get(j).top;	
			schangey[i] = sfinishy - sbeginy[i];
			stime[i] = 0;
		}  
		
		onSuccEnterFrame();
	}
}

function onSuccEnterFrame()
{
	var i,j,k;
	
	for(i=0,j=showList[tidx].size()-1;i<13;i++,j--)
	{ 
		//document.getElementById("aaa").innerHTML = j;
		if(i==0)
		{
			if(stime[i]<=duration)
			{
				showList[tidx].get(j).obj().style.left = Math.easeINOutCubic(stime[i]++,sbeginx,schangex,duration) + "px";
				showList[tidx].get(j).obj().style.top  = Math.easeINOutCubic(stime[i]++,sbeginy[i],schangey[i],duration) + "px";
			}
		}
		else if( stime[i-1] > duration/2 && stime[i] <= duration) 
		{
			showList[tidx].get(j).obj().style.zIndex = tz+i;
			showList[tidx].get(j).obj().style.left = Math.easeINOutCubic(stime[i]++,sbeginx,schangex,duration) + "px";
			showList[tidx].get(j).obj().style.top  = Math.easeINOutCubic(stime[i]++,sbeginy[i],schangey[i],duration) + "px";
        }
	}
 
    var stimer=setTimeout("onSuccEnterFrame()",10);
    if(stime[12] > duration)
    { 
		clearTimeout(stimer);
		for(k=0;k<13;k++)	stime[k]=0;
		judgeSuccess(tidx);
		if(si<6)		
			onOffSend(1,si);
		gameStart = 1;
		coverDiv.style.display="none";
	}
        
        //document.getElementById("flag").innerHTML=flag;
        //flag++;
} 
/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

//提示节点-----------------------------------------
function hintNode(fi,ti)
{
	this.fi = fi;
	this.ti = ti; 
	this.set = function(sfi,sti)
	{
		this.fi = sfi;
		this.ti = sti; 
	};		
}

var hNode = new hintNode(-1,-1); 
function hint()
{
	if(gameStart)
	{ 
		var breakFlag;
		var haveHint = 0;
		for(var i=0;i<10;i++)
		{ 
			if(showList[i].size()==0) continue;
			
			var j=showList[i].activeStart;
			for(var k=0;k<10;k++)
			{
				breakFlag = 0; 
				if(k==i) continue;
				if(showList[k].size()==0)
				{
					haveHint=1;
					if( (i>hNode.fi) ||  ((i == hNode.fi) &&  (k > hNode.ti)) )
					{	
						hNode.set(i,k);
						blinkHint(i,k);
						breakFlag = 1;
					}	
				}
				else if(showList[k].last().value - showList[i].get(j).value ==1)
				{ 
					haveHint=1;
					if( (i>hNode.fi) ||  ((i == hNode.fi) &&  (k > hNode.ti)) )
					{	
						hNode.set(i,k);
						blinkHint(i,k);
						breakFlag = 1;
					}	 
				}
				if(breakFlag) break;
			}
			if(breakFlag) break;
			for(n=i+1;n<10;n++)
				if(showList[n].size())	break;
			if(n==10 && haveHint) 
			{ 
				hNode.set(-1,-1); 
				hint();
			}	
		}
		if(haveHint==0)
			if(ISIE&&sound) WMP.URL="sounds/127.wav"; 		 
	}
}



var blankHint = document.createElement("div");
blankHint.style.cssText="width:71px;height:96px;background:none;position:absolute;left:0px;top:0px;";

function blinkHint(i,k)
{
	var a=1;
	var j=showList[i].activeStart;
	
	list = document.getElementById("list"+(k+1)); 
	
	if(ISIE&&sound) WMP.URL="sounds/126.wav"; 
	function b(){
			gameStart = 0;
				var l;
				if(a==1)
				{ 
					for(l=j;l <showList[i].size(); l++)
					{
						showList[i].get(l).obj().style.background="url('http://jsspider.googlecode.com/svn/trunk/ig/images/reverse/t"+showList[i].get(l).type+"v"+showList[i].get(l).value+".gif') no-repeat";  
					}
				}
				if(a==2)
				{
					for(l=j;l < showList[i].size(); l++)
					{	
						showList[i].get(l).obj().style.background="url('http://jsspider.googlecode.com/svn/trunk/ig/images/normal/t"+showList[i].get(l).type+"v"+showList[i].get(l).value+".gif') no-repeat"; 
					}
					if(showList[k].size()==0)
					{
						list.appendChild(blankHint);
						blankHint.style.background = "url('http://jsspider.googlecode.com/svn/trunk/ig/images/reverse/listBg.gif') no-repeat"; 
					}
					else
					{
						showList[k].last().obj().style.background="url('http://jsspider.googlecode.com/svn/trunk/ig/images/reverse/t"+showList[k].last().type+"v"+showList[k].last().value+".gif') no-repeat"; 
					}
				}
				if(a==3)
				{
					if(showList[k].size()==0)
					{ 
						blankHint.style.background = "none"; 
					}
					else
					{
						showList[k].last().obj().style.background="url('http://jsspider.googlecode.com/svn/trunk/ig/images/normal/t"+showList[k].last().type+"v"+showList[k].last().value+".gif') no-repeat"; 	
					}			
				}
				a++;
				if(a>3) 
				{
					clearInterval(hintTime);
					gameStart=1;
					if(showList[k].size()==0) list.removeChild(blankHint);
				}
		}
	b();
	var hintTime = setInterval(b,250);  
}

function showAbout()
{
	document.getElementById("aboutDlg").style.display="block";
	onOffSend(0,si);
	coverDiv.style.display="block";
	document.getElementById("cover").onclick=function()
	{
		document.getElementById("aboutDlg").style.display = "none";
		onOffSend(1,si);
		coverDiv.style.display="none";
	}
}
function showHelp()
{
	coverDiv.style.display="block";
	document.getElementById("help").style.display="block";
	onOffSend(0,si);
	document.getElementById("cover").onclick=function()
	{
		document.getElementById("help").style.display = "none";
		onOffSend(1,si);
		coverDiv.style.display="none";
	}
}
